package action.ManagerAction;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by xuweijie on 2017/4/20.
 */
public class LoginAction extends ActionSupport implements ServletRequestAware{

    private HttpServletRequest request;

    @Override
    public String execute() throws Exception {

        String error=null;
        ServletContext context= ServletActionContext.getServletContext();
        //从request中获取FormAuthenticationFilter填充的异常信息，就是ShiroLoginFailure的全限定名
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        //根据Shiro返回的异常类信息判断，抛出并处理这个异常信息
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户不存在，请核对用户名";//如果UnknownAccountException抛出这个异常，表示账号不存在
            context.setAttribute("error",error);
        } else if (IncorrectCredentialsException.class.getName().equals(
                exceptionClassName)) {
            error = "用户名/密码错误";
            context.setAttribute("error",error);
        } else if (exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
            context.setAttribute("error",error);
        }

        //此方法不处理登陆成功，shiro认证成功会跳转到上一个路径
        //登陆失败，回到login页面
        return LOGIN;
    }

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request=httpServletRequest;
    }
}
